﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Tools
{
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class Singleton<T> where T : class//, new() //2010-09-27 去掉new() by 杜有发
    {
        private static T _instance = null;
        private static object _obj = new object();

        /// <summary>
        /// T一定要可以实例化,如果实例不存在，直接调用new方法进行创建
        /// </summary>
        public static T Instance
        {
            get
            {
                return GetInstance(null);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="generator"></param>
        /// <returns></returns>
        public static T GetInstance(Generator generator)
        {
            if (_instance == null)
            {
                lock (_obj)
                {
                    if (_instance == null)
                    {
                        if (generator == null)
                        {
                            _instance = Activator.CreateInstance<T>();//new T();
                            //2010-09-27 修改为Activator.CreateInstance<T>()，可以创建没有构造函数的实体 by 杜有发
                            //2010-09-30 CreateInstance也会调用默认的构造函数，如果存在的话
                        }
                        else
                            _instance = generator();
                    }
                }
            }
            return _instance;
        }

        /// <summary>
        /// 2010-08-17 增加 by 杜有发
        /// </summary>
        /// <returns></returns>
        public delegate T Generator();

        /// <summary>
        /// 销毁对象
        /// </summary>
        public static void Dispose()
        {
            lock (_obj)
            {
                _instance = null;
            }
        }
    }
}
